package com.ef.web.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.ef.domain.Attachment;
import com.ef.service.AttachmentService;

public class UploadAction extends BaseAction<Attachment> {

	private static final long serialVersionUID = 1L;

	private static final int BUFFER_SIZE = 16 * 1024;

	private AttachmentService attachmentService;

	private File file;

	private String fileFileName;

	private String fileContentType;

	private String savePath;
	
	private int fileSizeLimit;

	public String upload() throws IOException {
		Result result = new Result();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
		SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String currentMonth = format.format(new Date());
		
		String newFileName = format2.format(new Date()) + (int)Math.random()*20;
		Attachment attachment = new Attachment();
		if (file != null) {
			long fileSize = file.length();
			if (fileSize > fileSizeLimit) {
				result.setSizeMsg("this file is too large.");
			} else {
				
				
				File path = new File(ServletActionContext.getServletContext()
						.getRealPath(this.getSavePath())
						+ "/"+currentMonth);
				if(!path.exists()){
					path.mkdirs();
				}
				
				File dst = new File(ServletActionContext.getServletContext()
						.getRealPath(this.getSavePath())
						+ "/"+currentMonth+"/"+newFileName+getExtenion(fileFileName));
				
				copy(file,dst);
				
				attachment.setName(this.getFileFileName());
				attachment.setRealName(this.getSavePath() + "/" + currentMonth
						+ "/" + newFileName + getExtenion(fileFileName));
				attachment.setSize(String.valueOf( fileSize));
				attachment.setUploadTime(new Date());
				attachment.setUploader(super.getSessionUser());
				
				attachmentService.save(attachment);
				
				
				
			}

		} else {

		}

		HttpServletResponse response = getResponse();
		
		StringBuilder  backString = new StringBuilder();
		backString.append("{");
		backString.append("id:'"+attachment.getId()+"',");
		backString.append("name:'"+attachment.getName()+"',");
		backString.append("realName:'"+attachment.getRealName()+"',");
		backString.append("size:'"+attachment.getSize()+"',");
		backString.append(result.toString());
		backString.append("}");
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8"); 
		response.getWriter().write(backString.toString());
		return NONE;
	}

	private  String getExtenion(String fileName){
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}
	
	private void copy(File src, File dst) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(dst),
					BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public String delete(){
		Attachment entity  = this.getModel();
		
		attachmentService.delete(entity);
		return NONE;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public AttachmentService getAttachmentService() {
		return attachmentService;
	}

	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}

	public int getFileSizeLimit() {
		return fileSizeLimit;
	}

	public void setFileSizeLimit(int fileSizeLimit) {
		this.fileSizeLimit = fileSizeLimit;
	}
	
	class Result {
		private String sizeMsg;
		private String otherMsg;
		
		public String toString(){
			return "sizeMsg:'"+this.sizeMsg+"',otherMsg:'"+this.otherMsg+"'";
		}

		public String getSizeMsg() {
			return sizeMsg;
		}

		public void setSizeMsg(String sizeMsg) {
			this.sizeMsg = sizeMsg;
		}

		public String getOtherMsg() {
			return otherMsg;
		}

		public void setOtherMsg(String otherMsg) {
			this.otherMsg = otherMsg;
		}
		
	}

}
